package com.yb.guigu.pick.mobile.sender.sender;

import com.yb.guigu.pick.core.bean.GuiguMobileProperties;
import com.yb.guigu.pick.mobile.sender.bean.MobileSenderRequest;
import com.yb.guigu.pick.mobile.sender.bean.MobileSenderResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;


/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/6/11 20:11
 * FileName: IGuiguMainSender
 * Description:
 */

public class MobileSenderImpl implements IMobileSender {

    @Autowired
    GuiguMobileProperties guiguMobileProperties;

    RestTemplate restTemplate=new RestTemplate();

    @Override
    public MobileSenderResponse send(MobileSenderRequest mobileSenderRequest) {
        String type = mobileSenderRequest.getType();


        if(!StringUtils.hasText(type)){
            return MobileSenderResponse.builder().success(false).uuid(mobileSenderRequest.getUuid()).error("type不能为空").build();
        }

        if(!StringUtils.hasText(mobileSenderRequest.getTemplate())){
            return MobileSenderResponse.builder().success(false).uuid(mobileSenderRequest.getUuid()).error("模板类型不能为空").build();
        }

        return this.doSend(mobileSenderRequest);
    }


    private MobileSenderResponse doSend(MobileSenderRequest senderRequest){

        MultiValueMap<String,Object> map=new LinkedMultiValueMap<>();

        String template = senderRequest.getTemplate();

        template = guiguMobileProperties.getTemplate().get(template);
        Object[] args = senderRequest.getArgs();
        String content= String.format(template, args);
        map.add("account",guiguMobileProperties.getAppId());
        map.add("password",guiguMobileProperties.getAppKey());
        map.add("mobile",senderRequest.getSendTo());
        map.add("content",content);
        map.add("format","json");
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.add("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

        HttpEntity<?> httpEntity=new HttpEntity<>(map,httpHeaders);

        ResponseEntity<String> result = restTemplate.postForEntity(guiguMobileProperties.getUrl(), httpEntity, String.class);

        System.out.println(result);

        return MobileSenderResponse.builder().uuid(senderRequest.getUuid()).success(true).content(result.getBody()).build();
    }
}
